<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
class ProductController extends \App\Http\Controllers\AdminController{
    /**
     * 产品列表
     * @return type
     */
    public function index() {
        $products = \App\Models\Product::whereIn('status', [1])->whereIn('ptype', [1, 2])->orderBy('ptype', 'asc')->orderBy('id', 'asc')->paginate();
        $areas = \App\Models\Area::orderBy('sort', 'asc')->get();
        foreach($areas as $val) {
            $area[$val->id] = $val->name;
        }
        $assign = compact('products', 'area');
        return view('admin.product.index', $assign);
    }
    /**
     * 修改/删除产品
     * @param Request $request
     * @param type $id
     * @param type $status
     * @return type
     */
    public function edit(Request $request, $id, $status=false) {
        $product = \App\Models\Product::find($id);
        if (!$product) {
            return \Illuminate\Support\Facades\Response::json([
                'status'    => 0,
                'info'      => '商品不存在'
            ]);
        }
        if ($status === '0') {
            $product->status = 0;
            $product->save();
            return \Illuminate\Support\Facades\Response::json([
                'status'    => 1,
                'info'      => '删除成功'
            ]);
        }
        if ($request->ajax()) {
            $product->name = $request->input('name');
            $product->price = $request->input('price');
            $product->desc = $request->input('desc');
            $product->ptype = $request->input('ptype');
            $product->area = $request->input('area');
            $product->pfav = $request->input('pfav');
            $product->pcateid = $request->input('pcateid');
            $product->lot = $request->input('lot');
            $product->sort = $request->input('sort');
            $product->save();
            return \Illuminate\Support\Facades\Response::json([
                'status'    => 1,
                'info'      => '修改成功'
            ]);
        }
        $area = \App\Models\Area::orderBy('sort', 'asc')->get();
        $pcate = \App\Models\Pcate::orderBy('sort', 'asc')->get();
        $assign = compact('product', 'area', 'pcate');
        return view('admin.product.edit', $assign);
    }
    /**
     * 添加新产品
     */
    public function add(Request $request) {
        if ($request->ajax()) {
            return \App\Models\Product::addProduct($request);
        }
        $area = \App\Models\Area::orderBy('sort', 'asc')->get();
        $pcate = \App\Models\Pcate::orderBy('sort', 'asc')->get();
        $assign = compact('area', 'pcate');
        return view('admin.product.add', $assign);
    }
}
